<?php

//微信服务层

namespace app\admin\service;

use app\common\Common;
use app\model\Applet;
use app\model\DataMaterial;
use think\facade\Cache;
use think\facade\Db;

class MaterialService
{
    private $AppKey;//账号
    private $DataMaterialModel;
    public function __construct(DataMaterial $DataMaterialModel)
    {
        $this->AppKey =config('hugeamount.apiKey');
        $this->DataMaterialModel = $DataMaterialModel;
    }
    /**
     * 素材列表
     *
     * @return void
     */
    public function getMaterialList($params)
    {

        if(empty($this->AppKey)) {
            return [];
        }
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        //获取数据
        $redisTodayData = $redisYesterdayData = $data = $where = [];
        for($i = 0;$i < count($this->AppKey);$i++) {
            $data_today = json_decode($redis->get('oceanengine_business_material_analysis_data_today:'.$this->AppKey[$i]), true);
            $data_yesterday = json_decode($redis->get('oceanengine_business_material_analysis_data_yesterday:'.$this->AppKey[$i]), true);
            if(!empty($data_today)) {
                foreach($data_today['data'] as $key=>$value){
                    if(!empty($redisTodayData[$key])){
                        foreach($value as $k=>$v){
                            if(isset($redisTodayData[$key][$k])&&!in_array($k,['title','material_id','created_at','video_time'])){
                                $redisTodayData[$key][$k] = round($redisTodayData[$key][$k] +$v,2);
                            }
                        }
                    }else{
                        $redisTodayData[$key] = $value;
                    }
                }
            }
            if(!empty($data_yesterday)) {
                foreach($data_yesterday['data'] as $key=>$value){
                    if(!empty($redisYesterdayData[$key])){
                        foreach($value as $k=>$v){
                            if(isset($redisYesterdayData[$key][$k])&&!in_array($k,['title','material_id','created_at','video_time'])){
                                $redisYesterdayData[$key][$k] = round($redisYesterdayData[$key][$k] +$v,2);
                            }
                        }
                    }else{
                        $redisYesterdayData[$key] = $value;
                    }
                }
            }
        }

        $offset = ($page - 1) * $limit;
        if(!empty($params['start_time'])&&!empty($params['end_time'])){
            $where['date']=['>=',date('Ymd',strtotime($params['start_time']))];
            $where['date']=['<=',date('Ymd',strtotime($params['end_time']))];
        }
        //获取表中所有数据
        $materialList = $this->getMaterialCount($where);
        if(empty($data_today) && empty($materialList)) {
            return [];
        }
        //基础字段
        $arr_key_name = [
            'material_id' => '',
            'title' => '',
            'created_at' => '',
            'cover_url' => '',
            'video_url' => '',
            'video_time' => 0,
            'related_ad_cnt' => 0,
            'related_creative_cnt' => 0,
            'related_promotion_cnt' => 0,

            'today_stat_cost' => 0,
            'today_show_cnt' => 0,
            'today_click_cnt' => 0,
            'today_ctr' => 0,
            'today_active_cost' => 0,
            'today_active' => 0,
            'today_cpc_platform' => 0,
            'today_conversion_cost' => 0,
            'today_convert_cnt' => 0,
            'today_conversion_rate' => 0,

            'count_stat_cost' => 0,
            'count_show_cnt' => 0,
            'count_click_cnt' => 0,
            'count_ctr' => 0,
            'count_active_cost' => 0,
            'count_active' => 0,
            'count_cpc_platform' => 0,
            'count_conversion_cost' => 0,
            'count_convert_cnt' => 0,
            'count_conversion_rate' => 0,
            'yesterday_stat_cost' => 0,
            'yesterday_show_cnt' => 0,
            'yesterday_click_cnt' => 0,
            'yesterday_ctr' => 0,
            'yesterday_active_cost' => 0,
            'yesterday_active' => 0,
            'yesterday_cpc_platform' => 0,
            'yesterday_conversion_cost' => 0,
            'yesterday_convert_cnt' => 0,
            'yesterday_conversion_rate' => 0,
        ];
        //今日数据为基准
        if(!empty($redisTodayData)) {
            foreach($redisTodayData as $key => $val) {
                $data[$key] = $arr_key_name;
                $data[$key]['material_id'] = (string)$key;
                $data[$key]['created_at'] = date('Y-m-d H:i:s', strtotime($val['created_at']));//创建时间
                $data[$key]['title'] = $val['title'];//素材名称
                $data[$key]['today_show_cnt'] = $val['show_cnt'];//展示数
                $data[$key]['today_click_cnt'] = $val['click_cnt'];//点击数
                $data[$key]['today_ctr'] = $val['ctr'];//点击率
                $data[$key]['today_active_cost'] = $val['active_cost'];//激活成本
                $data[$key]['today_active'] = $val['active'];//激活数
                $data[$key]['today_cpc_platform'] = $val['cpc_platform'];//平均客单价
                $data[$key]['today_conversion_cost'] = $val['conversion_cost'];//平均转化成本
                $data[$key]['today_convert_cnt'] = $val['convert_cnt'];//转化数
                $data[$key]['today_conversion_rate'] = $val['conversion_rate'];//转化率
                $data[$key]['related_ad_cnt'] = $val['related_ad_cnt'];//关联计划数
                $data[$key]['related_creative_cnt'] = $val['related_creative_cnt'];//关联创意数
                $data[$key]['related_promotion_cnt'] = $val['related_promotion_cnt'];//关联广告数
                $data[$key]['today_stat_cost'] = $val['stat_cost'];//消耗
            }
        }
        //条件累计数据
        if(!empty($materialList)) {
            foreach($materialList as $key => $val) {
                if(empty($data[$val['material_id']])) {
                    $data[$val['material_id']] = $arr_key_name;
                    $data[$val['material_id']]['material_id'] = (string)$val['material_id'];
                    $data[$val['material_id']]['title'] = $val['title'];//素材名称
                    $data[$val['material_id']]['created_at'] = date('Y-m-d H:i:s', strtotime($val['created_at']));//创建时间
                    $data[$val['material_id']]['related_ad_cnt'] = $val['related_ad_cnt'];//关联计划数
                    $data[$val['material_id']]['related_creative_cnt'] = $val['related_creative_cnt'];//关联创意数
                    $data[$val['material_id']]['related_promotion_cnt'] = $val['related_promotion_cnt'];//关联广告数
                }
                $data[$val['material_id']]['count_show_cnt'] = $val['show_cnt'];//展示数
                $data[$val['material_id']]['count_click_cnt'] = $val['click_cnt'];//点击数
                $data[$val['material_id']]['count_ctr'] = $val['ctr'];//点击率
                $data[$val['material_id']]['count_active_cost'] = $val['active_cost'];//激活成本
                $data[$val['material_id']]['count_active'] = $val['active'];//激活数
                $data[$val['material_id']]['count_cpc_platform'] = $val['cpc_platform'];//平均客单价
                $data[$val['material_id']]['count_conversion_cost'] = $val['conversion_cost'];//平均转化成本
                $data[$val['material_id']]['count_convert_cnt'] = $val['convert_cnt'];//转化数
                $data[$val['material_id']]['count_conversion_rate'] = $val['conversion_rate'];//转化率
                $data[$val['material_id']]['count_stat_cost'] = $val['stat_cost'];//消耗
            }
        }
        //昨日数据整合
        if(!empty($redisYesterdayData)) {
            foreach($redisYesterdayData as $key => $val) {
                if(empty($data[$key])) {
                    $data[$key] = $arr_key_name;
                    $data[$key]['material_id'] = (string)$key;
                    $data[$key]['title'] = $val['title'];//素材名称
                    $data[$key]['created_at'] = date('Y-m-d H:i:s', strtotime($val['created_at']));//创建时间
                    $data[$key]['related_ad_cnt'] = $val['related_ad_cnt'];//关联计划数
                    $data[$key]['related_creative_cnt'] = $val['related_creative_cnt'];//关联创意数
                    $data[$key]['related_promotion_cnt'] = $val['related_promotion_cnt'];//关联广告数
                }
                $data[$key]['yesterday_show_cnt'] = $val['show_cnt'];//展示数
                $data[$key]['yesterday_click_cnt'] = $val['click_cnt'];//点击数
                $data[$key]['yesterday_ctr'] = $val['ctr'];//点击率
                $data[$key]['yesterday_active_cost'] = $val['active_cost'];//激活成本
                $data[$key]['yesterday_active'] = $val['active'];//激活数
                $data[$key]['yesterday_cpc_platform'] = $val['cpc_platform'];//平均客单价
                $data[$key]['yesterday_conversion_cost'] = $val['conversion_cost'];//平均转化成本
                $data[$key]['yesterday_convert_cnt'] = $val['convert_cnt'];//转化数
                $data[$key]['yesterday_conversion_rate'] = $val['conversion_rate'];//转化率
                $data[$key]['yesterday_stat_cost'] = $val['stat_cost'];//消耗
            }
        }

        $data = array_values($data);
        if(!empty($params['material_id'])) {
            $data =$this->searchArr($data,$params['material_id']);
        }
        if(!empty($params['name'])) {
            $data =$this->searchArr($data,$params['name']);
        }
        if(!empty($params['sort'])&&!empty( $params['orderby'])) {
            $order=$params['orderby']=='asc'? SORT_ASC : SORT_DESC;
            $data =$this->arraySort($data,$params['sort'],$order);
        }else{
            $data =$this->arraySort($data,'today_stat_cost');
        }
        $list = array_splice($data, $offset, $limit);
        $material_ids = [];
        foreach($list as $key => $val) {
            $material_ids[] = $val['material_id'];
        }
        $images = Db::name('data_oceanengine_material_upload')->whereIn('material_id', $material_ids)->where(['status' => 1])->field('material_id,cover_url,video_url,video_duration')->select();
        foreach($images as $key => $val) {
            foreach($list as $k => $v) {
                if($v['material_id'] == $val['material_id']) {
                    $list[$k]['cover_url'] = 'https://oss.sybyn.top/'.$val['cover_url'];
                    $list[$k]['video_url'] = 'https://oss.sybyn.top/'.$val['video_url'];
                    $list[$k]['video_time'] = $val['video_duration'];
                }
            }

        }
        $total = count($data);
        $totalPage = ceil($total / $limit);
        return  $list = ['total' => $total, 'total_page' => $totalPage, 'data' => $list];
    }
    /**
     * 获取全部数据
     *
     * @param [type] $params
     * @return array
     */
    public function getMaterialCount($where = [])
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(2);
        $data = json_decode($redis->get('material_data_count'.md5(json_encode($where))), true);
        if(empty($data)) {
            $field = "
            company_key,
            company_name,
            material_id,
            title,
            created_at,
            sum(show_cnt) as show_cnt,
            sum(click_cnt) as click_cnt,
            sum(ctr) as ctr,
            sum(active_cost) as active_cost,
            sum(active) as active,
            sum(cpc_platform) as cpc_platform,
            sum(conversion_cost) as conversion_cost,
            sum(convert_cnt) as convert_cnt,
            sum(conversion_rate) as conversion_rate,
            sum(related_ad_cnt) as related_ad_cnt,
            sum(related_creative_cnt) as related_creative_cnt,
            sum(related_promotion_cnt) as related_promotion_cnt,
            sum(stat_cost) as stat_cost
            ";
            $data = $this->DataMaterialModel->where($where)->group('material_id')->field($field)->select();

            $extime = strtotime(date('Y-m-d', strtotime('+1 day')) . ' 00:00:00');
            $redis->set('material_data_count'.md5(json_encode($where)), json_encode($data), $extime - time());

        }
        return $data;
    }

    /**
     * 在数组中模糊搜索给定的值
     * @param $data
     * @param $keyword
     * @return array
     */
    public function searchArr($data, $keyword)
    {
        $arr = [];
        foreach($data as $key => $values) {
            foreach($values as $k => $v) {
                if (preg_match("/{$keyword}/i", (string)$v)) {
                    $arr[]=$values;
                }
            }
        }
        return $arr;
    }

         /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC 
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC) {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}
